package playtools.core;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


public class ProcessStarter {
	
    protected List<String> commands;   //�����б�
    protected File pwd;                //��ǰĿ¼
    protected OutputStream stdout;
    protected OutputStream stderr;
    protected InputStream stdin;
    protected Map<String, String> envs;

    public ProcessStarter cmds(String... args) {
        return cmds(Arrays.asList(args));
    }

    public ProcessStarter cmds(File program, String... args) {
        commands = new ArrayList<String>(args.length+1);
        commands.add(program.getPath());
        commands.addAll(Arrays.asList(args));
        return this;
    }

    public ProcessStarter cmds(List<String> args) {
        commands = new ArrayList<String>(args);
        return this;
    }


    public List<String> cmds() {
        return commands;
    }

    public ProcessStarter pwd(File workDir) {
        this.pwd = workDir;
        return this;
    }

    public ProcessStarter pwd(String workDir) {
        return pwd(new File(workDir));
    }

    public File pwd() {
        return pwd;
    }

    public ProcessStarter stdout(OutputStream out) {
        this.stdout = out;
        return this;
    }
    
    public OutputStream stdout() {
        return stdout;
    }

    /**
     * Controls where the stderr of the process goes.
     * By default, it's bundled into stdout.
     */
    public ProcessStarter stderr(OutputStream err) {
        this.stderr =  err;
        return this;
    }

    public OutputStream stderr() {
        return stderr;
    }

    /**
     * Controls where the stdin of the process comes from.
     * By default, <tt>/dev/null</tt>.
     */
    public ProcessStarter stdin(InputStream in) {
        this.stdin = in;
        return this;
    }

    public InputStream stdin() {
        return stdin;
    }

    public ProcessStarter envs(Map<String, String> overrides) {
        this.envs = overrides;
        return this;
    }

    public Map<String, String> envs() {
        return envs;
    }
    
    /**
     * Starts the process and waits for its completion.
     */
    public int join(String name){
    	Proc proc = new Proc(this.commands.toArray(new String[0]), envs, stdin,stdout, stderr,pwd);
    	return proc.join(name);
    }

    /**
     * Copies a {@link ProcStarter}.
     */
    public ProcessStarter copy() {
    	ProcessStarter rhs = new ProcessStarter().cmds(commands).pwd(pwd).stdin(stdin).stdout(stdout).stderr(stderr).envs(envs);
        return rhs;
    }
}
